package com.regex.web.controller;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.regex.web.base.BaseController;
import com.regex.web.common.excel.ExportExcel;
import com.regex.web.common.excel.ImportExcel;
import com.regex.web.entity.sys.DeptDTO;
import com.regex.web.entity.sys.UserDTO;
import com.regex.web.service.sys.IDeptService;
import com.regex.web.utils.AjaxUtil;
import com.regex.web.utils.Contant;
import com.regex.web.utils.QueryResult;
import com.regex.web.vo.ImportResultVO;
import com.regex.web.vo.LayTableDataVO;
import com.regex.web.vo.ResultVO;
import com.regex.web.vo.TreeVO;

/**
 * <p>
 * 组织机构 前端控制器
 * </p>
 *
 * @author mhy
 * @since 2020-08-03
 */
@Controller
@RequestMapping("sys/dept")
public class DeptController extends BaseController {

	private final static Logger logger = LoggerFactory.getLogger(DeptController.class);
	
	@Autowired
	private IDeptService IDeptService;
	
//	@Autowired
//    private IVillageService villageService;
//	
//	@Autowired
//	private IDeptVillageService deptVillageService;
	/**
	 * 分页查询
	 * @param page
	 * @param model
	 * @param deptDTO
	 * @return
	 */
	@GetMapping("show")
	public String show() {
		return "sys/dept/show1";
	}
	
	
	@RequestMapping("getPageData")
	public void getPageData(HttpServletResponse response,
			DeptDTO deptDTO, String limit, String page) {
		LayTableDataVO<DeptDTO> result = new LayTableDataVO<DeptDTO>();
		try {
			
			QueryWrapper<DeptDTO> param = new QueryWrapper<DeptDTO>();
			if(StringUtils.isNotEmpty(deptDTO.getName())) {
				param.like("name", deptDTO.getName());
			}
			if(StringUtils.isNotEmpty(deptDTO.getParentId())) {
                param.eq("parent_id", deptDTO.getParentId());
            }
			param.orderByDesc("create_time");
			Page<DeptDTO> pageParam = new Page<DeptDTO>();
			if (StringUtils.isEmpty(limit)) {
				limit = Contant.NONMAL_PAGE_SIZE_TEN + "";
			}
			if (StringUtils.isEmpty(page)) {
				page = Contant.NONMAL_PAGE_START + "";
			}
			pageParam.setSize(Integer.parseInt(limit));
			pageParam.setCurrent(Integer.parseInt(page));
			
	        QueryResult<DeptDTO> pageResult = IDeptService.page(pageParam, param);
			for(DeptDTO dept : pageResult.getDatas()) {
			    if(dept.getParentId().equals("0")) {
			        dept.setParentName("无");
			    } else {
			        DeptDTO deptParentTmp = IDeptService.getById(dept.getParentId());
			        dept.setParentName(deptParentTmp.getName());
			        
			    }
			}
			result.setData(pageResult.getDatas());
			result.setCode(0);
			result.setCount(pageResult.getTotalDataCount());
		} catch (Exception e) {
			result.setCode(500);
			AjaxUtil.ajaxJsonSucMessage(response, result);
			e.printStackTrace();
		}
		AjaxUtil.ajaxJsonSucMessage(response, result);
	}
	
	/**
	 * 编辑/新增
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("input")
    public String toSave(@ModelAttribute("id")  String id) {
        return "sys/dept/input";
    }
    
    @GetMapping("get/{id}")
	@ResponseBody
    public ResultVO<DeptDTO> getData(@PathVariable String id) {
	    DeptDTO deptDTO = IDeptService.getById(id);
        return ResultVO.success(deptDTO, ResultVO.SUCCESS, ResultVO.errors.get(ResultVO.SUCCESS));
    }
    
    /**
	 * 保存
	 * @param deptDTO
	 * @param response
	 */
    @PostMapping("save")
	@ResponseBody
	public ResultVO<String> save(@Valid  @RequestBody DeptDTO deptDTO, HttpServletResponse response,
	        HttpServletRequest request) {
		ResultVO<String> result = new ResultVO<String>();
		boolean flag = false;
		if(StringUtils.isNotEmpty(deptDTO.getId())) {
			deptDTO.setUpdateTime(new Date());
			UserDTO userDTO = getUser();
			deptDTO.setUpdateBy(userDTO.getId() + "");
			flag = IDeptService.updateById(deptDTO);
			if(flag) {
            	return ResultVO.success();
            }
		} else {
		    UserDTO userDTO = getUser();
            deptDTO.setCreateBy(userDTO.getId() + "");
			deptDTO.setIsDel(Contant.is_del_undelete);
			deptDTO.setUpdateTime(new Date());
			deptDTO.setCreateTime(new Date());
			flag = IDeptService.save(deptDTO);
			if(flag) {
            	return ResultVO.success();
            }
		}
		return result;
	}
    
    /**
     * 
     * 功能描述: <br>
     * 获取组织树
     *
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = {"getZTree"})
    public void getZTreeJson(HttpServletResponse response) {
        List<TreeVO> datas = getZTreeList();
        TreeVO rootTree = new TreeVO();
        rootTree.setId("0");
        rootTree.setName("根目录");
        rootTree.setParentId("0");
        datas.add(rootTree);
        AjaxUtil.ajaxJsonSucMessage(response, datas);
    }
    
    public List<TreeVO> getZTreeList() {
        QueryWrapper<DeptDTO> queryWrapper = new QueryWrapper<DeptDTO>();
//        queryWrapper.eq("parent_id", "0");
        List<DeptDTO> menuDTOList = IDeptService.list(queryWrapper);
        List<TreeVO> ZTreeVOList = new ArrayList<TreeVO>();
        for(DeptDTO deptDTO : menuDTOList) {
            TreeVO treeVO = new TreeVO();
            treeVO.setId(deptDTO.getId());
            treeVO.setName(deptDTO.getName());
            treeVO.setParentId(deptDTO.getParentId());
            ZTreeVOList.add(treeVO);
        }
        return ZTreeVOList;
    }
	
	/**
	 * 详情
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("detial")
    public String detial(String id, Model model) {
        try {
	        if(StringUtils.isNotEmpty(id)) {
	        	DeptDTO deptDTO = IDeptService.getById(id);
	        	if(deptDTO.getParentId().equals("0")) {
	        	    deptDTO.setParentName("无");
                } else {
                    DeptDTO deptParentTmp = IDeptService.getById(deptDTO.getParentId());
                    deptDTO.setParentName(deptParentTmp.getName());
                    
                }
	            model.addAttribute("deptDTO", deptDTO);
	        }
        } catch (Exception e) {
			e.printStackTrace();
			logger.error("detial page is Exception!");
		}
        return "sys/dept/detial";
    }
	
	/**
	 * 删除
	 * @param id
	 * @param response
	 */
	@RequestMapping("del")
    public void del(String id, HttpServletResponse response) {
        int n = 0;
        try {
	        if(StringUtils.isNotEmpty(id)) {
	        	boolean flag = IDeptService.removeById(id);
	        	if(flag) {
	        		n = 1;
	        	}
	        } else {
	        	n = 2;
	        }
        } catch (Exception e) {
			e.printStackTrace();
			logger.error("del page is Exception!");
		}
        AjaxUtil.ajaxJsonSucMessage(response, n);
    }
    
    /**
	 * 导出
	 * @param response
	 * @param deptDTO
	 * @return
	 */
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public void exportFile(HttpServletResponse response, @ModelAttribute("deptDTO") DeptDTO deptDTO) {
        try {
            QueryWrapper<DeptDTO> param = new QueryWrapper<DeptDTO>();
			if(StringUtils.isNotEmpty(deptDTO.getName())) {
				param.eq("name", deptDTO.getName());
			}
			param.orderByDesc("create_time");
        	String fileName = "数据"+(new Date()).getTime()+".xlsx";
            
            List<DeptDTO> datas = IDeptService.list(param);
            new ExportExcel("数据", DeptDTO.class).setDataList(datas).write(response, fileName).dispose();
        } catch (Exception e) {
        	logger.error("exportFile page is Exception!");
            e.printStackTrace();
        }
        
    }
    
    
     /**
     * 
     * 功能描述: <br>
     * 下载导入模板
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "importTemplate")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "组织机构信息导入模板.xlsx";
            List<DeptDTO> list = Lists.newArrayList(); 
            list.add(new DeptDTO());
            new ExportExcel("组织机构信息数据", DeptDTO.class, 2).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/sys/dept/show";
    }

    
    /**
     * 
     * 功能描述: <br>
     * 去导入界面
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @GetMapping("toImport")
    public String toImport() {
        return "sys/dept/import_excel";
    }
    
    /**
     * 
     * 功能描述: <br>
     * 导入
     *
     * @param file
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("importFile")
    @ResponseBody
    public ResultVO<ImportResultVO> importFile(MultipartFile file, @RequestParam(required = false, value="param") String param) {
        JSONObject json = JSON.parseObject(param);
        logger.error(json!=null?json.toJSONString():"");
        int successNum=0;
        int failureNum=0;
        StringBuilder failureMsg=new StringBuilder();
        ImportExcel ei;
        List<DeptDTO> list;
        try {
            ei = new ImportExcel(file, 1, 0);
            list=ei.getDataList(DeptDTO.class);
        } catch (Exception e1) {
            e1.printStackTrace();
            list = Lists.newArrayList(); 
        }
        for(DeptDTO data : list) {
               data.setUpdateTime(new Date());
               data.setIsDel(Contant.is_del_undelete);
               data.setCreateTime(new Date());
               try {
                   IDeptService.saveOrUpdate(data);
                   successNum++;
               } catch (Exception e) {
                   e.printStackTrace();
                   failureNum++;
                   failureMsg.append("数据：").append(JSON.toJSONString(data)).append("导入失败；");
               }
        }
        return ResultVO.success(ImportResultVO.result(successNum, failureNum, failureMsg.toString()), ResultVO.SUCCESS, ResultVO.errors.get(ResultVO.SUCCESS));
    }
    
//    @RequestMapping("toSaveVillage")
//    public String toSaveRole(String id, Model model) {
//        DeptDTO deptDTO = IDeptService.getById(id);
//        
//        QueryWrapper<VillageDTO> queryWrapper = new QueryWrapper<VillageDTO>(); 
//        List<VillageDTO> allVillageList = villageService.list(queryWrapper);
//        for(VillageDTO villageDTO : allVillageList) {
//            String isChecked = "0";
//            if(StringUtils.isNotEmpty(id)) {
//                QueryWrapper<DeptVillageDTO> queryWrapper1 = new QueryWrapper<DeptVillageDTO>(); 
//                queryWrapper1.eq("dept_id", id);
//                queryWrapper1.eq("village_id", villageDTO.getId());
//                int count = deptVillageService.count(queryWrapper1);
//                if(count > 0) {
//                    isChecked = "1";
//                }
//            } 
//            villageDTO.setIsChecked(isChecked);
//        }
//        model.addAttribute("allVillageList", allVillageList);
//        
//        model.addAttribute("deptDTO", deptDTO);
//        return "sys/dept/set_village";
//    }
//    
//    @PostMapping("saveDeptVllage")
//    @ResponseBody
//    public ResultVO<String> saveDeptVllage(@Valid  @RequestBody DeptVillageVO deptVillageVO, HttpServletResponse response,
//            HttpServletRequest request) {
//        DeptDTO deptDTO = IDeptService.getById(deptVillageVO.getDeptId());
//        if(deptDTO == null) {
//            return ResultVO.error("数据不存在!");
//        }
//        String villageIdArr[] =  deptVillageVO.getVillageId().split(",");
//        
//        QueryWrapper<DeptVillageDTO> queryWrapper = new QueryWrapper<DeptVillageDTO>();
//        queryWrapper.eq("dept_id", deptVillageVO.getDeptId());
//        deptVillageService.remove(queryWrapper);
//        DeptVillageDTO deptVIllageTmp = DeptVillageDTO.getInstance();
//        List<DeptVillageDTO> deptVillageList = Lists.newArrayList();
//        for(String villageId : villageIdArr) {
//            deptVIllageTmp = DeptVillageDTO.getInstance(); 
//            deptVIllageTmp.setVillageId(villageId);
//            deptVIllageTmp.setDeptId(deptVillageVO.getDeptId());
//            deptVillageList.add(deptVIllageTmp);
//        }
//        deptVillageService.saveBatch(deptVillageList);
//        return ResultVO.success();
//    }
	
}
